package com.raylu.util

import com.alibaba.fastjson.JSON
import com.alibaba.fastjson.serializer.SerializeConfig
import com.raylu.bean.Person
import org.apache.http.HttpHost
import org.elasticsearch.action.bulk.{BulkRequest, BulkResponse}
import org.elasticsearch.action.index.{IndexRequest, IndexResponse}
import org.elasticsearch.client.{RequestOptions, RestClient, RestClientBuilder, RestHighLevelClient}
import org.elasticsearch.common.xcontent.XContentType

import java.util.Properties
import scala.collection.mutable

/**
 *
 * Description:
 *
 * Create by lucienoz on 2021/12/3.
 * Copyright © 2021 lucienoz. All rights reserved.
 */
object MyEsUtil {
	val esRHLClient : RestHighLevelClient = builder()

	def builder() : RestHighLevelClient = {
		val properties : Properties = PropertiesUtil.load ( "config.properties" )
		val restClientBuilder : RestClientBuilder = RestClient.builder ( new HttpHost ( properties.getProperty("es.host"), properties.getProperty("es.port").toInt ) )

		new RestHighLevelClient ( restClientBuilder )
	}

	def save(index : String, id : String, source : Any) : Unit = {
		val indexRequest : IndexRequest = new IndexRequest ().index ( index ).id ( id )
		indexRequest.source ( JSON.toJSONString ( source, new SerializeConfig ( true ) ), XContentType.JSON )
		val response : IndexResponse = esRHLClient.index ( indexRequest, RequestOptions.DEFAULT )
		println ( response.status () )

	}


	/**
	 *
	 * @param indexName
	 * @param list
	 */
	def bulkSave(indexName : String, list : List[(String, Any)]) : String = {
		//index : String, id : String, source : Any
		//		BulkRequest bulkRequest, RequestOptions options
		val bulkRequest = new BulkRequest ()
		for ((id,source) <- list) {
			val indexRequest : IndexRequest = new IndexRequest ()
				.index(indexName)
				.source ( JSON.toJSONString ( source, new SerializeConfig ( true ) ), XContentType.JSON )
				.id(id)
			bulkRequest.add ( indexRequest )

		}
		val response : BulkResponse = esRHLClient.bulk ( bulkRequest, RequestOptions.DEFAULT )
		println("ES 是否插入成功== "+response.status())
		response.status().toString

	}

	def destroy(): Unit ={
		esRHLClient.close()
	}


	def main(args : Array[String]) : Unit = {
		val tuples : List[(String, Any)] = List[(String, Any)]( ("1", Person ( "1", 2 )), ("2", Person ( "2", 2 )), ("3", Person ( "3", 2 )) )
		bulkSave("person",tuples)

		save("person1","1",Person ( "1", 2 ))
		destroy()

	}

}
